package Server.Service;

import Server.DAO.FutureDAO;
import Server.DAO.UserDAO;
import Server.domain.Future;
import Server.domain.User;

public class DealService {
	
	UserDAO userDao;
	FutureDAO futureDao;
	User currentUser;
	Future future;
	
	public DealService(){
		userDao = new UserDAO();
		futureDao = new FutureDAO();
		
	}
	
   public double deal(String message){
	   
	   //处理来自客户端的message
	   String tempNum[] = new String[5];
	   tempNum = message.split("`");  //tempNum数组中存放的依次为：<buy>//username //期货代码//成交手数//每手的点数（当前期货价值）
	   double tempFutureNum = Double.valueOf(tempNum[3]);
	   double tempFutureDealPoint = Double.valueOf(tempNum[4]);
	   
	   double accountMoney = -1;//当前账号余额
	   
	   currentUser = userDao.getUserByUsernameAndPassword("kitty","123");
	   future = new Future(currentUser.getUserId(),tempNum[2],tempFutureNum,tempFutureDealPoint);
	   /* <buy>操作
	    1、更新数据库Future表
	    2、计算当前账号余额
	    3、更新数据库User表updateMoneyByUserId;
	   */
	   
	   /* <sell>操作
	    1、更新数据库Future表：获取oldPrice及更新期货数量
		2、计算当前用户余额 money+（tempNum【4】-oldPrice）*tempNum【3】*300
		3、更新数据库User表的money值
	   */
	   
	   if(tempNum[0].equals("<buy>")){
		    futureDao.buy(future);
		    accountMoney = currentUser.getMoney()-tempFutureNum*tempFutureDealPoint*100;
		}else if(tempNum[0].equals("<sell>")){
		    double oldPrice = futureDao.sell(future);
		    accountMoney = currentUser.getMoney()+(tempFutureDealPoint-oldPrice)*tempFutureNum*100;
	    }
	   System.out.print(accountMoney);
	   userDao.updateUserMoneyByUserId(currentUser.getUserId(), accountMoney);   
	   return accountMoney;
   }
}
